#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>

int main(int argc, const char *argv[])
{
    /*
  socket tcp server
    创建套接字
      int lfd = socket
    绑定本地IP和端口
      struct sockaddr_in serv;
      serv.port = htons(port)
      serv.IP = htonl(INADDR_ANY)
      bind(lfd, &serv, sizeof(serv));
    监听
      listen(lfd, 128);
    等待接收连接请求
      struct sockaddr_in client;
      int len = sizeof(client)
      int cfd = accept(lfd, &client, &len)
        cfd-用于通信的
    通信
      接收数据：read/recv
      发送数据：write/send
    关闭：
      close(lfd)
      close(cfd)
  */
    // 创建套接字
    int lfd = socket(AF_INET, SOCK_STREAM, 0);
    // 绑定本地IP和端口
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_port = htons(8888);
    serv.sin_addr.s_addr = INADDR_ANY;
    serv.sin_family = AF_INET;

    // 设置端口复用
    int flag = 1;
    setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    int ret = bind(lfd, (struct sockaddr *)&serv, sizeof(serv));
    if (ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    // 监听
    listen(lfd, 128);

    // 等待接收连接请求
    struct sockaddr_in client;
    int len = sizeof(client);
    // cfd 通信套接字
    socklen_t cfd = accept(lfd, (struct sockaddr *)&client, &len);
    if (cfd != -1)
    {
        printf("connect successful");
    }
    while (1)
    {
        char buf[1024];
        read(cfd, buf, sizeof(buf));
        printf("recv %s\n", buf);
        int l = strlen(buf);
        for (int i = 0; i < l; ++i)
        {
            buf[i] = toupper(buf[i]);
        }
        // 转化成大写发送回去
        write(cfd, buf, sizeof(buf));
        printf("send %s\n", buf);
    }
    close(lfd);
    close(cfd);

    return 0;
}
